package com.jrx.anytxn.param.job.investor.file.config;

import com.jrx.anytxn.param.config.InvestorFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.job.investor.file.step.MergeInvestorFileListener;
import com.jrx.anytxn.param.service.investor.IInvestorParamFileService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @program: 联合贷文件合并
 * @description:
 * @author: xiaoyu.jing
 * @date: 2020-06-08 16:40
 **/
@Configuration
public class MergeInvestorFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(MergeInvestorFileConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private InvestorFileConfig investorFileConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IInvestorParamFileService fileService;
    @Autowired
    private MergeInvestorFileListener mergeInvestorFileListener;

    @Bean
    public Job mergeInvestorFileJob() throws Exception {
        return jobBuilderFactory.get("mergeInvestorFileJob")
                .listener(mergeInvestorFileListener)
                .start(mergeInvestorFileStep())
                .build();
    }

    @Bean
    public Step mergeInvestorFileStep() throws IOException {
        return stepBuilderFactory.get("mergeInvestorFileStep")
                .tasklet(mergeInvestorFileStepTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet mergeInvestorFileStepTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.debug("分库文件合并开始。。。。。。");
            String filePath = investorFileConfig.getInvestorFilePath();
            String fileName = investorFileConfig.getInvestorFileName();

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            fileService.mergeFile(org,filePath,fileName);

            logger.debug("报送分库文件合并处理完成");
            return RepeatStatus.FINISHED;
        };
    }
}
